package com.wdh.kjs.activity;

import android.app.AlertDialog;
import android.content.Intent;
import android.content.SharedPreferences;
import android.os.Bundle;
import android.os.CountDownTimer;
import android.support.annotation.Nullable;
import android.text.method.HideReturnsTransformationMethod;
import android.text.method.PasswordTransformationMethod;
import android.view.View;
import android.widget.Button;
import android.widget.CheckBox;
import android.widget.EditText;
import android.widget.ImageView;
import android.widget.LinearLayout;
import android.widget.TextView;

import com.google.gson.Gson;
import com.lidroid.xutils.HttpUtils;
import com.lidroid.xutils.exception.HttpException;
import com.lidroid.xutils.http.RequestParams;
import com.lidroid.xutils.http.ResponseInfo;
import com.lidroid.xutils.http.callback.RequestCallBack;
import com.lidroid.xutils.http.client.HttpRequest;
import com.wdh.kjs.R;
import com.wdh.kjs.http.Httpurl;
import com.wdh.kjs.http.response.MyCookieStore;
import com.wdh.kjs.model.JsonModel;
import com.wdh.kjs.model.PlatformInfoForAppHtml;
import com.wdh.kjs.model.PlatformInfoForAppModel;
import com.wdh.kjs.util.EditTextLengthUtil;
import com.wdh.kjs.util.PhonenumUtil;
import com.wdh.kjs.util.ToastUtils;

import org.apache.http.impl.client.DefaultHttpClient;

/**
 * Created by CQH on 2016/4/21.
 */
public class RegisterNowActivity extends BaseTopActivity implements View.OnClickListener {
    private EditText resigist_phone;
    private EditText resigist_code;
    private EditText resigist_recode;
    private EditText resigist_codding;
    private TimeCount time;
    private Button register_getmsg1;
    private JsonModel jsonModel;
    private Button register;
    private CheckBox register_check;

    private ImageView pwdVisible;
    private boolean pwd_Isvisble = false;
    private ImageView rePwdVisible;
    private boolean repwd_Isvisble = false;

    private TextView tv_register_agreement;
    @Override
    protected void onCreate(@Nullable Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.register);
        initTopBar("注册");
        time = new TimeCount(60000*3, 1000);
        initview();
        initwidge();
    }

    private void initwidge() {
        register_getmsg1.setOnClickListener(this);
        register.setOnClickListener(this);
        pwdVisible.setOnClickListener(this);
        rePwdVisible.setOnClickListener(this);
        tv_register_agreement.setOnClickListener(this);
    }

    private void initview() {
        resigist_phone = (EditText) findViewById(R.id.resigist_phone);
        resigist_code = (EditText) findViewById(R.id.resigist_code);
        register_check = (CheckBox) findViewById(R.id.register_check);
        resigist_recode = (EditText) findViewById(R.id.resigist_recode);
        resigist_codding = (EditText) findViewById(R.id.resigist_codding);
        register_getmsg1 = (Button) findViewById(R.id.register_getmsg1);
        register = (Button) findViewById(R.id.register);
        pwdVisible = (ImageView) findViewById(R.id.PwdVisible);

        rePwdVisible = (ImageView) findViewById(R.id.rePwdVisible);

        tv_register_agreement=(TextView)findViewById(R.id.tv_register_agreement);
    }

    public void onClick(View v) {
        String phoneNum = resigist_phone.getText().toString().trim();
        switch (v.getId()) {
            case R.id.register_getmsg1: {
                if (PhonenumUtil.isMobileNO(phoneNum) == false) {
                    falseDialogShow("请输入正确的手机号码！");
                    return;
                }
                time.start();
                intcode();
                break;
            }
            case R.id.register: {
                int pwdlen = EditTextLengthUtil.check_length(resigist_code.getText().toString());
                int repwdlen = EditTextLengthUtil.check_length(resigist_recode.getText().toString());
                String pwdPrompt = EditTextLengthUtil.check_numAndAlphabet(resigist_code.getText().toString());
                if (PhonenumUtil.isMobileNO(phoneNum) == false) {
                    falseDialogShow("请输入正确的手机号码！");
                    return;
                }
                if (resigist_code.getText().toString().equals("")) {
                    falseDialogShow("请输入密码！");
                } else if (pwdlen != 0) {
                    if (pwdlen > 0) {
                        falseDialogShow("密码位数多于" + EditTextLengthUtil.max_length + "位");
                    } else {
                        falseDialogShow("密码位数少于" + EditTextLengthUtil.min_length + "位");
                    }
                } else if (pwdPrompt.length() > 0) {
                    falseDialogShow(pwdPrompt);
                } else if (resigist_recode.getText().toString().equals("")) {
                    falseDialogShow("请输入确认密码！");
                } else if (resigist_code.getText().toString().equals(resigist_recode.getText().toString())) {
                    if (register_check.isChecked()) {
                        intweb();
                    } else {
                        ToastUtils.showShort(RegisterNowActivity.this, "请阅读协议！");
                    }
                } else {
                    ToastUtils.showShort(RegisterNowActivity.this, "两次密码不一致！");
                }
                break;
            }
            case R.id.PwdVisible: {
                int index=resigist_code.getSelectionStart();
                pwd_Isvisble = !pwd_Isvisble;
                if (pwd_Isvisble == true) {
                    //设置密码可见
                    resigist_code.setTransformationMethod(HideReturnsTransformationMethod.getInstance());
                    pwdVisible.setImageResource(R.drawable.visual);
                } else {//设置密码不可见
                    resigist_code.setTransformationMethod(PasswordTransformationMethod.getInstance());
                    pwdVisible.setImageResource(R.drawable.eye_icon);
                }
                resigist_code.setSelection(index);
                break;
            }
            case R.id.rePwdVisible: {
                int index=resigist_recode.getSelectionStart();
                repwd_Isvisble = !repwd_Isvisble;
                if (repwd_Isvisble == true) {
                    //设置密码可见
                    resigist_recode.setTransformationMethod(HideReturnsTransformationMethod.getInstance());
                    rePwdVisible.setImageResource(R.drawable.visual);
                } else {//设置密码不可见
                    resigist_recode.setTransformationMethod(PasswordTransformationMethod.getInstance());
                    rePwdVisible.setImageResource(R.drawable.eye_icon);
                }
                resigist_recode.setSelection(index);
                break;
            }
            case R.id.tv_register_agreement:{
                platformInfoForApp();
                break;
            }
            default:{
                break;
            }
        }
    }
    private void intweb() {
        {
            HttpUtils http = new HttpUtils();
            http.configCookieStore(MyCookieStore.cookieStore);
            RequestParams params = new RequestParams();
            params.addBodyParameter("phoneNumber", resigist_phone.getText().toString());
            params.addBodyParameter("userLoginId", resigist_phone.getText().toString());
            params.addBodyParameter("password", resigist_code.getText().toString());
//            params.addBodyParameter("emailAddress","742051747@qq.com" );
            params.addBodyParameter("verificationCode", resigist_codding.getText().toString());

            http.send(HttpRequest.HttpMethod.POST, Httpurl.URL_REGIST, params, new RequestCallBack<String>() {

                @Override
                public void onSuccess(ResponseInfo<String> responseInfo) {


                    Gson gson = new Gson();
                    jsonModel = gson.fromJson(responseInfo.result, JsonModel.class);
                    SharedPreferences.Editor editor = getSharedPreferences("logininfo", MODE_PRIVATE).edit();
                    editor.putString("loginToken", jsonModel.getPartyId());
                    editor.putString("nickName", "");
                    editor.putString("phoneNumber", "");
                    editor.putString("mima", resigist_code.getText().toString());
                    editor.commit();
                    if (jsonModel.getPartyId() == null) {
                        ToastUtils.showShort(RegisterNowActivity.this, "请重新注册！");

                    } else {
                        Intent intent = new Intent(RegisterNowActivity.this, RegisterSuccessActivity.class);

                        startActivity(intent);
                        ToastUtils.showShort(RegisterNowActivity.this, "注册成功！");
                        finish();
                    }


                }

                @Override
                public void onFailure(HttpException error, String msg) {

                    ToastUtils.showShort(RegisterNowActivity.this, "网络异常！");
                }
            });
//
        }
    }

    private void intcode() {

        RequestParams params = new RequestParams();
        params.addBodyParameter("phoneNumber", resigist_phone.getText().toString());
        final HttpUtils http = new HttpUtils();
        http.send(HttpRequest.HttpMethod.POST, Httpurl.URL_CODDING, params, new RequestCallBack<String>() {

            @Override
            public void onSuccess(ResponseInfo<String> responseInfo) {


                Gson gson = new Gson();
                jsonModel = gson.fromJson(responseInfo.result, JsonModel.class);
//                    if (jsonModel.success) {
                DefaultHttpClient dh = (DefaultHttpClient) http.getHttpClient();
                MyCookieStore.cookieStore = dh.getCookieStore();

//                    }


            }

            @Override
            public void onFailure(HttpException error, String msg) {

                ToastUtils.showShort(RegisterNowActivity.this, "网络异常！");
            }
        });


    }

    private void falseDialogShow(String hint) {
        View dialog = (LinearLayout) getLayoutInflater().inflate(R.layout.view_dialog_false, null);
        Button bt_dialog_false_negative = (Button) dialog.findViewById(R.id.bt_dialog_false_negative);
        Button bt_dialog_false_positive = (Button) dialog.findViewById(R.id.bt_dialog_false_positive);
        TextView tv_dialog_false_hint = (TextView) dialog.findViewById(R.id.tv_dialog_false_hint);
        tv_dialog_false_hint.setText(hint);
        AlertDialog.Builder builder = new AlertDialog.Builder(this);
        builder.setView(dialog);
        builder.create();
        final AlertDialog dialogShow = builder.show();
        bt_dialog_false_negative.setOnClickListener(new android.view.View.OnClickListener() {

            @Override
            public void onClick(View v) {
                dialogShow.dismiss();
            }
        });
        bt_dialog_false_positive.setOnClickListener(new android.view.View.OnClickListener() {

            @Override
            public void onClick(View v) {
                dialogShow.dismiss();
//                updateLoginPassword_inputmsg.setText("");
            }
        });
    }

    private void trueDialogShow(String hint) {
        View dialog = (LinearLayout) getLayoutInflater().inflate(R.layout.view_dialog_true, null);
        TextView tv_dialog_false_hint = (TextView) dialog.findViewById(R.id.tv_dialog_true_hint);
        tv_dialog_false_hint.setText(hint);
        AlertDialog.Builder builder = new AlertDialog.Builder(this);
        builder.setView(dialog);
        builder.create();
        final AlertDialog dialogShow = builder.show();

    }

    class TimeCount extends CountDownTimer {
        public TimeCount(long millisInFuture, long countDownInterval) {
            super(millisInFuture, countDownInterval);
        }

        @Override
        public void onFinish() {// 计时完毕
            register_getmsg1.setText("发送验证码");
            register_getmsg1.setClickable(true);
        }

        @Override
        public void onTick(long millisUntilFinished) {// 计时过程
            register_getmsg1.setClickable(false);//防止重复点击
            register_getmsg1.setText(millisUntilFinished / 1000 + "s后可重新获取");
        }
    }

    private void platformInfoForApp(){
        RequestParams params = new RequestParams();
        params.addBodyParameter("sign", "8");
        HttpUtils httpUtils = new HttpUtils();
        httpUtils.send(HttpRequest.HttpMethod.POST, Httpurl.URL_Platform_Inf_For_App, params, new RequestCallBack<String>() {
            @Override
            public void onSuccess(ResponseInfo<String> responseInfo) {
                Gson gson = new Gson();
                PlatformInfoForAppModel pifam = gson.fromJson(responseInfo.result, PlatformInfoForAppModel.class);
                if(!pifam.isSuccess()){
                    falseDialogShow2(pifam.getMsg());
                    return;
                }
                PlatformInfoForAppHtml pifah=pifam.getResult().get(0);
                PlatformInfoForAppHtml.htmlStr=pifah.getContent();
                Intent intent=new Intent(RegisterNowActivity.this,RegisterAgreementActivity.class);
                startActivity(intent);
            }

            @Override
            public void onFailure(HttpException error, String msg) {
                falseDialogShow("网络异常");
            }
        });
    }

    private void falseDialogShow2(String hint) {
        View dialog = getLayoutInflater().inflate(R.layout.touzixinxi, null);
//        Button bt_dialog_false_negative = (Button) dialog.findViewById(R.id.bt_dialog_false_negative);
//        Button bt_dialog_false_positive = (Button) dialog.findViewById(R.id.bt_dialog_false_positive);
        TextView tv_dialog_false_hint = (TextView) dialog.findViewById(R.id.touzixinxi);
        tv_dialog_false_hint.setText(hint);
        AlertDialog.Builder builder = new AlertDialog.Builder(this);
        builder.setView(dialog);
        builder.create();
        final AlertDialog dialogShow = builder.show();
        tv_dialog_false_hint.setOnClickListener(new android.view.View.OnClickListener() {

            @Override
            public void onClick(View v) {
                dialogShow.dismiss();
            }
        });
//        bt_dialog_false_positive.setOnClickListener(new android.view.View.OnClickListener() {
//
//            @Override
//            public void onClick(View v) {
//                dialogShow.dismiss();
//            }
//        });
    }
}
